package com.bs.manager05.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bs.manager05.entity.User;
import com.bs.manager05.mapper.UserMapper;
import com.bs.manager05.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bs.manager05.utils.RedisUtils;
import com.bs.manager05.utils.TokenUtils;
import com.bs.manager05.utils.UUIDFactory;
import com.bs.manager05.utils.exception.NoUserException;
import com.bs.manager05.utils.exception.PasswordEqualException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author yao
 * @since 2022-12-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    AuthenticationManager manager;

    @Resource
    RedisUtils utils;

    @Resource
    PasswordEncoder encoder;

    @Resource
    UserDetailsServiceImpl service;

    @Override
    public String login(User user) {


       /* String a=new BCryptPasswordEncoder().encode(user.getPwd());
        user.setPwd(a);*/


        UsernamePasswordAuthenticationToken usernamePassword=new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());

        Authentication authenticate = manager.authenticate(usernamePassword);
        if(authenticate==null){
            throw new NoUserException("用户名或密码错误");
        }
        String token= UUIDFactory.UUID();
        utils.set(token,user, TokenUtils.TOKEN_TIME);


        return token;
    }
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }
}
